package com.dstz.form.rest.controller;

import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.dstz.base.api.aop.annotion.CatchErr;
import com.dstz.base.api.response.impl.ResultMsg;
import com.dstz.base.core.util.StringUtil;
import com.dstz.base.rest.BaseController;
import com.dstz.form.constants.BooleanConstants;
import com.dstz.form.manager.FormCustSqlFieldsManager;
import com.dstz.form.manager.FormCustSqlManager;
import com.dstz.form.manager.FormCustSqlRelationManager;
import com.dstz.form.model.custsql.FormCustSql;
import com.dstz.form.model.custsql.FormCustSqlFields;
import com.dstz.form.model.custsql.FormCustSqlRelation;
import com.dstz.form.request.IdRequest;
import com.dstz.form.util.SqlUtil;
import com.dstz.form.vo.SqlFieldsVO;
import com.dstz.sys.util.ContextUtil;

/**
 * @description:自定义列表 的控制层
 * @company:宇宙大魔王
 * @author:xianggang
 * @date:2019-08-31 12:21:58
 */
@RestController
@RequestMapping("/form/formCustSql")
public class FormCustSqlController extends BaseController<FormCustSql> {
	
	protected Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Resource
	FormCustSqlManager formCustSqlManager;
	
	@Resource
	FormCustSqlFieldsManager formCustSqlFieldsManager;
	
	@Resource
	FormCustSqlRelationManager formCustSqlRelationManager;
	
	@Override
	protected String getModelDesc() {
		return "自定义列表";
	}
	
	/**
	 * 保存
	 */
	@RequestMapping("/parseSql")
	@CatchErr
	public ResultMsg<List<SqlFieldsVO>> parseSql(@RequestBody FormCustSql formCustSql) throws Exception {
		
		return formCustSqlManager.parseSql(formCustSql);
	}
	
	/**
	 * 给sql的字段加上别名
	 * @param tmSqlDef
	 * @return
	 * @throws Exception
	 * @return ResultMsg<String>
	 * @author xianggang
	 * @date 2019年9月1日 下午1:29:40
	 */
	@RequestMapping(value = "/addAliases")
	@CatchErr
	public ResultMsg<String> addAliases(@RequestBody FormCustSql formCustSql) throws Exception {
		return SqlUtil.addAliases(formCustSql.getSqlContent());
	}
	
	/**
	 * 保存
	 */
	@RequestMapping("/save")
	@CatchErr
	public ResultMsg<String> save(@RequestBody FormCustSql formCustSql) throws Exception {
		return formCustSqlManager.save(formCustSql);
	}
	
	/**
	 * 查询自定义列表详情
	 * @author xianggang
	 */
	@RequestMapping("/get")
	@CatchErr
	public ResultMsg<FormCustSql> get(@RequestParam String id) throws Exception {
		
		if (StringUtil.isEmpty(id)) {
			return ResultMsg.ERROR("ID不能为空");
		}
		
		FormCustSql formCustSql = formCustSqlManager.get(id);
		if (formCustSql == null) {
			return ResultMsg.ERROR("自定义列表不存在,id:" + id);
		}
		// 查询字段列表
		List<FormCustSqlFields> fieldsList = formCustSqlFieldsManager.getListBySqlId(id);
		formCustSql.setFieldsList(fieldsList);
		
		FormCustSqlRelation custForm =  formCustSqlRelationManager.getByFormKey(formCustSql.getFormKey());
		formCustSql.setCustForm(custForm);
		
		return ResultMsg.SUCCESS(formCustSql);
	}
	
	/**
	 * 根据别名获取自定义sql对象
	 * @author xianggang
	 */
	@RequestMapping("/getByCode")
	@CatchErr
	public ResultMsg<FormCustSql> getByCode(@RequestParam String code) throws Exception {
		
		if (StringUtil.isEmpty(code)) {
			return ResultMsg.ERROR("ID不能为空");
		}
		
		FormCustSql formCustSql = formCustSqlManager.getByCode(code, true);
		if (formCustSql == null) {
			return ResultMsg.ERROR("自定义列表不存在,code:" + code);
		}
		
		return ResultMsg.SUCCESS(formCustSql);
	}
	
	/**
	* 批量删除
	*/
	@RequestMapping("/remove")
	@CatchErr
	public ResultMsg<String> remove(@RequestParam String id) throws Exception {
		
		String[] aryIds = StringUtil.getStringAryByStr(id);
		formCustSqlManager.removeCustSqlByIds(aryIds);
		
		return getSuccessResult(String.format("删除%s成功", getModelDesc()));
	}
	
	/**
	* 启用/发布
	*/
	@RequestMapping("/publish")
	@CatchErr
	public ResultMsg<String> publish(@RequestParam String id) throws Exception {
		
		logger.info("启用/发布自定义sql:{}", id);
		
		changeStatus(id, BooleanConstants.YES);
		return getSuccessResult("启动成功");
	}
	
	/**
	 * 停用/禁用
	 */
	@RequestMapping("/disabled")
	@CatchErr
	public ResultMsg<String> disabled(@RequestParam String id) throws Exception {
		
		logger.info("停用/禁用自定义sql:{}", id);
		
		int status = BooleanConstants.NO;
		changeStatus(id, status);
		
		return getSuccessResult("启动成功");
	}
	
	/**
	 * 导出到JSON文件
	 * @throws Exception 
	 */
	@RequestMapping("/export")
	public void export(IdRequest request, HttpServletResponse response) throws Exception {
		
		logger.info("导出到JSON文件,ID:{}", request.getId());
		String id = request.getId();
		if (StringUtil.isEmpty(id)) {
			return;
		}
		
		ResultMsg<JSONObject> exportRsp = formCustSqlManager.export(request.getId());
		
		JSONObject exportData = exportRsp.getData();
		
		String fileName = new String(exportData.getString("fileName").getBytes("UTF-8"), "ISO8859-1");
		response.reset();
		// response.setContentType("application/octet-stream");
		response.setContentType("application/json;charset=UTF-8");
		response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".json");
		
		PrintWriter writer = response.getWriter();
		writer.write(exportData.getString("sqls"));
		writer.flush();
		writer.close();
		
	}
	
	/**
	 * 从JSON文件导入自定义SQL
	 * 最好是一个一个的导入
	 * @throws Exception 
	 */
	@RequestMapping("/import")
	@CatchErr
	public ResultMsg<String> importJson(MultipartHttpServletRequest request, HttpServletResponse response)
	        throws Exception {
		
		MultipartFile file = request.getFile("file");
		
		String json = new String(file.getBytes(), "UTF-8");
		
		return formCustSqlManager.importJson(json);
		
	}
	
	private void changeStatus(String id, int status) {
		String[] aryIds = StringUtil.getStringAryByStr(id);
		for (String sqlId : aryIds) {
			FormCustSql formCustSql = formCustSqlManager.get(sqlId);
			if (formCustSql != null) {
				formCustSql.setStatus(status);
				formCustSql.setUpdateTime(new Date());
				formCustSql.setUpdateBy(ContextUtil.getCurrentUserId());
				formCustSql.setUpdator(ContextUtil.getCurrentUserName());
			}
			formCustSqlManager.update(formCustSql);
		}
	}
	
}
